package com.wcarmon.life.command{

    import com.adobe.cairngorm.commands.ICommand
    import com.adobe.cairngorm.control.CairngormEvent;
	import mx.controls.Alert;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.IResponder;
	import com.wcarmon.life.model.LifeModelLocator;
	import com.wcarmon.life.event.*;
	import com.wcarmon.life.business.*;
	import mx.utils.ObjectUtil;
	
	
	
	public class SaveBlockFieldCommand implements ICommand, IResponder {
		include "../../includes/loggerSnippet.as";
		
		public var callbackScreen : Object; 
		
		public function execute( event : CairngormEvent ) : void { 
			var e : SaveBlockFieldEvent = SaveBlockFieldEvent( event );
			callbackScreen = e.callbackScreen;
			
			log.info('Block Field update attempt: id=' + e.block_id + ", field=" + e.block_field_name + ", new value=" + e.block_field_value);
			var delegate : SaveBlockFieldDelegate = new SaveBlockFieldDelegate(this);
			delegate.saveBlockField( e.block_id, e.block_field_name, e.block_field_value );			
		}
	
	 	public function result( event : Object ) : void {
			var e : ResultEvent = ResultEvent(event);
			
			if( e.result.errorCode == 0 && e.result.affected_rows == 1 ){
				log.info("Saved change to '"+e.result.block_field_name +"' for item #"+e.result.block_id);
				callbackScreen.doCallback();
				Alert.show("Saved change to '"+e.result.block_field_name +"' for item #"+e.result.block_id);
				
			}else if( e.result.errorCode == 0 && e.result.affected_rows == 0 ){
				callbackScreen.doCallback();
				Alert.show("No change made to item #" + e.result.block_id );
				
			}else{
				Alert.show("DB error #"+ e.result.errorCode +" while saving!");
				log.error("Mysql error #"+ e.result.errorCode +" while saving:\n" + e.result.errorDesc );
				log.error("Update Query:\n" + e.result.updateQuery );
				log.error("affected_rows = " + e.result.affected_rows);
			}
		}
		
	
		public function fault( event : Object ) : void {
			include "includes/FaultSnippet.as";
		}
	}
}